import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/model/comment.dart';

class GoodsCommentPage extends StatefulWidget {
  int spuId;

  GoodsCommentPage(this.spuId);

  @override
  State<StatefulWidget> createState() => GoodsCommentPageState(this.spuId);
}

class GoodsCommentPageState extends State<GoodsCommentPage> {
  int spuId;
  List<Comment> _comments = [];

  int _curPage = 1;
  RefreshListView _refreshListView;
  bool _showEmpty = false;

  GoodsCommentPageState(this.spuId);

  @override
  void initState() {
    super.initState();
    _getComments(spuId, 1);
  }

  @override
  Widget build(BuildContext context) {
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: ListView.builder(
        itemCount: _comments.length,
        itemBuilder: (context, index) {
          Comment comment = _comments[index];
          String reviewStr = "";
          if (comment != null && comment.review != null) {
            switch (comment.review) {
              case "well":
                reviewStr = "好评";
                break;
              case "normal":
                reviewStr = "中评";
                break;
              case "bad":
                reviewStr = "差评";
                break;
              default:
            }
          }
          return Container(
            color: Colors.white,
            padding: const EdgeInsets.all(15.0),
            margin: const EdgeInsets.only(bottom: 1.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    new Container(
                      width: 30.0,
                      height: 30.0,
                      margin: const EdgeInsets.only(right: 15.0),
                      decoration: new BoxDecoration(
                        color: Colors.grey,
                        borderRadius: new BorderRadius.circular(100.0),
                        image: new DecorationImage(
                            image: new CachedNetworkImageProvider(
                                comment.user != null &&
                                        comment.user.avatar != null
                                    ? comment.user.avatar
                                    : Api.defaultAvatar),
                            fit: BoxFit.fill),
                      ),
                    ),
                    Text(
                      comment.user != null && comment.user.nickname != null
                          ? comment.user.nickname
                          : "",
                      style:
                          TextStyle(fontSize: 15.0, color: ColorCommon.grey8),
                    ),
                  ],
                ),
                reviewStr != null && reviewStr.isNotEmpty
                    ? Container(
                        margin: const EdgeInsets.only(top: 10.0, bottom: 10.0),
                        child: Wrap(
                          spacing: 10.0,
                          children: <Widget>[
                            _getTagView(reviewStr, ColorCommon.red3,
                                ColorCommon.red3, ColorCommon.grey8),
                          ],
                        ),
                      )
                    : Container(),
                Text(
                  comment.content ?? "",
                  style: TextStyle(fontSize: 10.0, color: ColorCommon.grey8),
                ),
              ],
            ),
          );
        },
      ),
      showEmpty: _showEmpty,
      onReload: () {
        _getComments(spuId, 1);
      },
    );
    return Scaffold(
      appBar: _createAppBar(),
      body: Container(color: ColorCommon.grey5, child: _refreshListView),
    );
  }

  _createAppBar() {
    return new AppBar(
      elevation: 0.0,
      title: new Text("全部评论"),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[],
    );
  }

  Widget _getTagView(
      String text, Color bgColor, Color borderColor, Color textColor,
      {DecorationImage image}) {
    BoxDecoration decoration;
    if (image == null) {
      decoration = BoxDecoration(
          color: bgColor,
          border: Border.all(color: borderColor),
          borderRadius: BorderRadius.all(Radius.circular(100.0)));
    } else {
      decoration = BoxDecoration(image: image);
    }
    return Container(
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      decoration: decoration,
      child: Text(
        text,
        style: TextStyle(fontSize: 13.0, color: textColor),
      ),
    );
  }

  void _onRefresh(bool up) {
    if (up) {
      _getComments(spuId, 1);
    } else {
      _getComments(spuId, _curPage + 1);
    }
  }

  _getComments(int spuId, int page) {
    bool isGetNew = page == 1;
    Map<String, String> params = {
      "spu_id": spuId.toString(),
      "page": page.toString()
    };

    NetUtil.get(
        context,
        Api.comments,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : Comment.fromJson(e))
              ?.toList();
          setState(() {
            _showEmpty =
                isGetNew && (_dataList == null || _dataList.length <= 0);
            if (isGetNew) {
              _comments = _dataList;
            } else {
              _comments.addAll(_dataList);
            }
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            _showEmpty =
                isGetNew && (_comments == null || _comments.length <= 0);
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew);
          }
        });
  }
}
